<?php
/**
 * Created by 陈俊伟.
 * User: Administrator
 * Date: 2019-10-28
 * Time: 下午 2:52
 */

namespace App\Lib\Upload;

use App\Exceptions\InvalidRequestException;

class UploadHandle
{
    protected $ext = [];
    protected $dir = null;
    protected $type = null;
    protected $file = null;

    public function __construct($file, $type, $dir)
    {
        $this->file = $file;
        $this->type = $type;
        $this->dir = $dir;
    }


    public static function factory($name, ...$args)
    {
        $class = 'App\Lib\Upload' . '\\' . $name;

        $reflect = new \ReflectionClass($class);

        return $reflect->newInstanceArgs($args);
    }

    public function upload()
    {
        // 构建存储的文件夹规则，值如：uploads/images/avatars/201709/21/
        $folder_name = "upload/$this->dir/$this->type/";

        // 获取文件的后缀名，因图片从剪贴板里黏贴时后缀名为空，所以此处确保后缀一直存在
        $extension = strtolower($this->file->getClientOriginalExtension());

        if (!in_array($extension, $this->ext)) {
            throw new InvalidRequestException('不是图片文件');
        }
        // 拼接文件名，加前缀是为了增加辨析度，前缀可以是相关数据模型的 ID
        // 值如：1493521050_7BVc9v9ujP.png
        $filename = time() . '_' . str_random(10) . '.' . $extension;

        // 文件具体存储的物理路径，`public_path()` 获取的是 `public` 文件夹的物理路径。
        // 值如：/home/vagrant/Code/larabbs/public/uploads/images/avatars/201709/21/
        $folder_path = public_path() . '/' . $folder_name;
        // 将图片移动到我们的目标存储路径中
        $this->file->move($folder_path, $filename);
        $path = $folder_name . '/' . $filename;

        return config('app.url') . '/' . $path;
    }

    public function bsUpload()
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $this->file, $result)) {
            $type = $result[2];

            // 构建存储的文件夹规则，值如：uploads/images/avatars/201709/21/
            $folder_name = "upload/$this->dir/$this->type/";
            // 值如：1493521050_7BVc9v9ujP.png
            $filename = time() . '_' . str_random(10) . '.' . $type;

            $img_file = base64_decode(str_replace($result[1], '', $this->file));


            if (file_put_contents($_SERVER["DOCUMENT_ROOT"] . '/' . $folder_name . '/' . $filename, $img_file)) {
                return config('app.url') . '/'. $folder_name .  $filename;
            }

        }
        return null;

    }
}